import React from 'react';
import {StyleSheet, View, Keyboard} from 'react-native';
import Toast from 'react-native-easy-toast';

import api from '../../../common/api';

import SearchBar from './searchBar';
import History from './history';
import List from '../../../components/list';
import Loading from '../../../components/loading';
import ListEmptyComponent from '../../../components/listEmptyComponent';
import auth from '../../../common/auth';

export default class extends React.Component {
    state = {
        keywords: '',
        list: [],
        page: 1,
        page_size: 20,
        isFetching: false,
        hasMore: true,
        isShowHistory: false,
        searchHistory: [],
        hasResult: false                //是否已经搜索过
    };
    //设置关键字
    setKeywords = (keywords, call) => {
        this.setState({
            keywords
        }, () => {
            call && call();
        });
    };
    //重置当前页面
    resetPage = (callback) => {
        this.setState({
            list: [],
            page: 1,
            isFetching: false,
            hasMore: true,
            isShowHistory: false
        }, () => {
            callback && callback();
        });
    };
    //获取数据
    getData = () => {
        const {isFetching, page, page_size, list, keywords, hasMore} = this.state;
        if (isFetching || !hasMore || !keywords) {
            return;
        }
        Keyboard.dismiss();
        this.setState({
            isFetching: true
        });
        let data = {
            page,
            page_size,
            keywords
        };
        api({
            url: 'api/item/getItemListByPage',
            data
        })
            .then(data => {
                this.setState({
                    list: [...list, ...data],
                    page: page + 1,
                    hasMore: data.length >= page_size
                });
                this.saveHistory(keywords);
            })
            .catch(e => {
                this.showToast(e.msg);
            })
            .finally(() => {
                this.setState({
                    isFetching: false,
                    hasResult: true
                });
            });
    };

    //切换是否显示搜索历史
    toggleSearchHistory = (flag) => {
        const {searchHistory} = this.state;
        this.setState({
            isShowHistory: flag && searchHistory.length
        });
    };

    //添加搜索历史关键字
    saveHistory = (title) => {
        const {searchHistory} = this.state;
        let isExists = searchHistory.some(item => item === title);
        if (isExists) {
            return;
        }
        searchHistory.unshift(title);
        if (searchHistory.length > 20) {
            searchHistory.length = 20;
        }
        auth.setSearchHistory(searchHistory)
            .then(() => {
                this.checkHistory();
            });
    };

    //删除搜索历史关键字
    removeKeywords = (title) => {
        const self = this;
        const {searchHistory} = this.state;
        let newList = searchHistory.filter(item => item !== title);
        auth.setSearchHistory(newList)
            .then(() => {
                this.checkHistory(() => {
                    const {searchHistory} = self.state;
                    self.setState({
                        isShowHistory: searchHistory.length
                    });
                });
            });
    };

    //检查搜索历史
    checkHistory = (call) => {
        auth.getSearchHistory()
            .then(data => {
                const {searchHistory = []} = data;
                this.setState({
                    searchHistory
                }, () => {
                    call && call();
                });
            })
            .catch(() => {
                console.log('暂无数据');
            });
    };

    showToast = text => {
        this.refs.toast.show(text);
    };

    componentDidMount() {
        let self = this;
        this.checkHistory(() => {
            const {searchHistory} = self.state;
            self.setState({
                isShowHistory: searchHistory.length
            });
        });
    }

    render() {
        const {list, hasMore, isFetching, keywords, hasResult, isShowHistory, searchHistory} = this.state;
        const {navigation} = this.props;
        return (
            <View style={styles.container}>
                <SearchBar toggleSearchHistory={this.toggleSearchHistory}
                           navigation={navigation}
                           keywords={keywords}
                           resetPage={this.resetPage}
                           setKeywords={this.setKeywords}
                           getData={this.getData}
                           showToast={this.showToast}
                />
                {
                    isShowHistory ? <History toggleSearchHistory={this.toggleSearchHistory}
                                             removeKeywords={this.removeKeywords}
                                             searchHistory={searchHistory}
                                             resetPage={this.resetPage}
                                             setKeywords={this.setKeywords}
                                             getData={this.getData}
                                             showToast={this.showToast}/> : null
                }
                <List
                    list={list}
                    isFetching={isFetching}
                    hasMore={hasMore}
                    ListEmptyComponent={
                        hasResult ? ListEmptyComponent : <View/>
                    }
                    endReachedFn={this.getData}
                />
                <Loading isLoading={list.length === 0 && isFetching}/>
                <Toast ref="toast" position="center"/>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        backgroundColor: '#f6f6f6',
        flex: 1
    }
});
